import {Component, ViewChild, Directive, ElementRef, Input} from '@angular/core';
import {
  Events,
  AlertController,
  App,
  ModalController,
  NavController,
  Content,
  ActionSheetController,
  LoadingController
} from 'ionic-angular';
import {Storage} from '@ionic/storage';
import {Config} from '../../../providers/config';
import {DomSanitizer} from '@angular/platform-browser';
import _ from 'lodash';

import {Common} from "../../../providers/common";
import {BcwHomeListPage} from "./list.component";
import {BcwRuleService} from "./rule.service";

@Component({
  selector: 'page-bcw-rule',
  templateUrl: './rule.html',
  providers: [BcwRuleService]
})
export class BcwRulePage {
  moa_page_name: any = "page-bcw-rule";
  moa_page_explain: any = "BCW规则订阅";

  segment = "1";

  complementBtn = "";

  returnData = null;
  dataList = [];
  pushDataList = [];
  colorList = [];

  allRule = [];
  changeRule = [];
  ruleTree_level1 = [];
  ruleTree_level2 = [];
  ruleTree_level3 = [];
  ruleTree_level4 = [];
  ruleTree_level5 = [];

  badge_color_1 = "";
  badge_color_2 = "";
  badge_color_3 = "";
  badge_color_4 = "";
  badge_color_5 = "";

  loginid = '';
  boolFlagShow = true;
  lockShow = false;
  expandCard = {
    level1: false,
    level2: false,
    level3: false,
    level4: false,
    level5: false
  };
  email: any = {
    mailbosid: "",
    login: "",
    // 邮件标题
    bostitle: "BCW风控规则修改申请，请系统管理员及时响应",
    // 邮件内容
    content: "",
    // 收件人账号
    recievelist: "luodd,liangyl",
    // 密送账号
    secretlist: "",
    // 抄送账号
    otherlist: "",
    // 紧急
    urgency: 2,
    // 是否回执
    isreceipt: 0,
    // 附件
    attach: ""
  };

  keyWord = "";

  color = "#666666";

  constructor(public alertCtrl: AlertController,
              public app: App,
              public modalCtrl: ModalController,
              public navCtrl: NavController,
              public config: Config,
              private sanitizer: DomSanitizer,
              public events: Events,
              public storage: Storage,
              private common: Common,
              private actionSheetCtrl: ActionSheetController,
              private loadingCtrl: LoadingController,
              private as: ActionSheetController,
              private bcwRuleService: BcwRuleService) {
    this.storage.get("userInfo").then((user) => {
      this.loginid = user.loginid;
      this.loadDatas();
      console.log(user);
    });

  }

  loadFirstSegment() {
    // if(this.lockShow)
    // this.lockShow=false;
    // this.bcwRuleService.getRuleOfUser().subscribe((data) => {
    //   if (data) {
    //     this.dataList = data;
    //   }
    // });
  }

  loadDatas() {
    this.bcwRuleService.getSubScribeRule(this.loginid).subscribe((subdata) => {
      if (subdata) {
        this.dataList = subdata;
      }
      this.bcwRuleService.getRuleOfUserAll(this.loginid).subscribe((data) => {
        console.log(data);
        if (data) {
          this.returnData = data;
          this.badge_color_1 = "#434348";
          this.badge_color_2 = "#95CEFF";
          this.badge_color_3 = "#F5F16C";
          this.badge_color_4 = "#F7A35C";
          this.badge_color_5 = "#D9534F";
          this.colorList.push(this.badge_color_1);
          this.colorList.push(this.badge_color_2);
          this.colorList.push(this.badge_color_3);
          this.colorList.push(this.badge_color_4);
          this.colorList.push(this.badge_color_5);
          _.forEach(data, (d, index) => {
            data[index].l_ruleid = parseInt(data[index].l_ruleid);
            let flag = _.filter(this.dataList, {
              "vc_rulename": d.vc_rulename
            });
            if (flag.length) {
              data[index].l_wanted = false;
            } else {
              data[index].l_wanted = true;
              this.pushDataList.push(data[index]);
            }

          });
          console.log(this.pushDataList);
          this.ruleTree_level1 = _.filter(data, d => {
            if (d["vc_memo"] == "" || "1") {
              return true;
            }
          });
          this.ruleTree_level2 = _.filter(data, {"vc_memo": "2"});
          this.ruleTree_level3 = _.filter(data, {"vc_memo": "3"});
          this.ruleTree_level4 = _.filter(data, {"vc_memo": "4"});
          this.ruleTree_level5 = _.filter(data, {"vc_memo": "5"});
          setTimeout(() => {
            this.lockShow = true;
          }, 1000);

        }
      });
    });
  }

  searchInput(event) {
    console.log(this.keyWord);
    this.lockShow = false;
    if (this.keyWord) {
      let ruleTree: any = _.filter(this.returnData, data => {
        return data["vc_rulename"].indexOf(this.keyWord) > -1;
      });
      if (ruleTree) {
        if (ruleTree.vc_memo == '' || ruleTree.vc_memo == '1') {
          this.ruleTree_level1 = ruleTree;
        } else if (ruleTree.vc_memo == '2') {
          this.ruleTree_level2 = ruleTree;
        } else if (ruleTree.vc_memo == '3') {
          this.ruleTree_level3 = ruleTree;
        } else if (ruleTree.vc_memo == '4') {
          this.ruleTree_level4 = ruleTree;
        } else if (ruleTree.vc_memo == '5') {
          this.ruleTree_level5 = ruleTree;
        }
      }
    } else {
      this.ruleTree_level1 = _.filter(this.returnData, d => {
        if (d["vc_memo"] == "" || d["vc_memo"] == "1") {
          return true;
        }
      });
      this.ruleTree_level2 = _.filter(this.returnData, {"vc_memo": "2"});
      this.ruleTree_level3 = _.filter(this.returnData, {"vc_memo": "3"});
      this.ruleTree_level4 = _.filter(this.returnData, {"vc_memo": "4"});
      this.ruleTree_level5 = _.filter(this.returnData, {"vc_memo": "5"});
    }
    //timeout是上面的filter要1s内完成
    setTimeout(() => {
      this.lockShow = true;
    }, 1000);

  }

  chooseListType() {
    let allRule = this.ruleTree_level1.concat(this.ruleTree_level2).concat(this.ruleTree_level3).concat(this.ruleTree_level4).concat(this.ruleTree_level5);

    let alert = this.alertCtrl.create({
      title: "提醒",
      message: "确定规则订阅的修改？",
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          handler: () => {
            this.complementBtn = '';
          }
        },
        {
          text: '确定',
          handler: () => {
            this.complementBtn = '';
            let endChangeNoPushRule = [], endChangePushRule = [];
            let pushContent = '需要增加的规则列表为：';
            let noPushContent = '需要删除的规则列表为：';
            console.log(this.changeRule);
            _.forEach(this.changeRule, (item, index) => {
              let rule: any = _.filter(this.returnData, {"vc_rulename": item.vc_rulename});
              console.log(item.l_wanted != rule.l_wanted);
              if (item.l_wanted != rule.l_wanted) {
                if (item.l_wanted) {
                  endChangePushRule.push(item);
                  pushContent += item.vc_rulename + ',';
                  let rule=_.filter(this.pushDataList,{"vc_rulename": item.vc_rulename});
                  if(!rule.length){
                    this.pushDataList.push(item);
                  }
                } else {
                  let i=-1;
                  _.forEach(this.pushDataList,(data,index)=>{
                    if(data.vc_rulename==item.vc_rulename){
                       i=index;
                    }
                  });
                  if(i!=-1){
                    this.pushDataList.splice(i,1);
                  }
                  i=-1;
                  endChangeNoPushRule.push(item);
                  noPushContent += item.vc_rulename + ',';
                }
              }
            });
            //每次改变都排序一下
            this.pushDataList = _.sortBy(this.pushDataList, "vc_memo");
            this.pushDataList = _.reverse(this.pushDataList);

            pushContent = pushContent.substring(0, pushContent.length - 1) + "；";
            noPushContent = noPushContent.substring(0, noPushContent.length - 1) + "。";

            // let code='CN=A938493525/TI=nihao/OU=fengjk';
            // let name='dd';
            // let recievelist=this.common.formatContactListData(this.bcwRuleService.formatContactData(code,name));
            // this.email.recievelist=recievelist;
            this.email.login = this.loginid;
            this.email.content = pushContent + noPushContent;
            console.log(this.email);
            this.bcwRuleService.editEmail(this.email, 'send').subscribe(data => {
              console.log(data);
            });
          }
        }
      ]
    });
    alert.present();
  }

  showAdvancedQueryModal() {
    // let modal=this.modalCtrl.create(MarketingCreditQueryPage);
    // modal.onDidDismiss((data)=>{
    //   if(data){
    //     this.managerName=data.managerName||'';
    //     this.level=data.level||'';
    //     this.setListData(data.managerName,data.level);
    //   }
    // });
    // modal.present();
  }

  onSegmentChange(segmentEvent) {
    this.lockShow = false;
    if (segmentEvent.value == "2") {
      setTimeout(() => {
        this.lockShow = true;
      }, 500);
    }
  };

  openSubscribe(item) {
    if (this.lockShow) {
      let rule = _.filter(this.changeRule, {"vc_rulename": item.vc_rulename});
      // let obj = {
      //   flag: false,
      //   i: 0,
      //   l_wantedNow: false
      // }
      // _.forEach(this.changeRule, (data, index) => {
      //   if (data.vc_rulename == item.vc_rulename) {
      //     obj.flag = true;
      //     obj.i = index;
      //     obj.l_wantedNow = item.l_wanted;
      //     return;
      //   }
      // })
      // if (!obj.flag) {
      //   this.changeRule.push(item);
      // } else {
      //   this.changeRule[obj.i].l_wanted = obj.l_wantedNow;
      // }
      if (!rule.length) {
        this.changeRule.push(item);
      } else {
        rule["l_wanted"] = item.l_wantedNow;
      }
      console.log(this.changeRule);
    }
    // console.log(this.lockShow);
    if (this.complementBtn !== '完成' && this.lockShow) {
      this.complementBtn = '完成';
    }
  }


  expandCardEvent(item) {
    this.expandCard[item] = !this.expandCard[item];
  }

  moreOp(item) {
    let buttons = [];
    buttons.push({
      text: "设置优先级",
      handler: () => {
        let alert = this.alertCtrl.create({
          title: '设置规则优先级',
          inputs: [
            {
              name: "vc_memo",
              label: "1 普通",
              value: "1",
              checked: false,
              type: "radio"
            }, {
              name: "vc_memo",
              label: "2 一般",
              value: "2",
              checked: false,
              type: "radio"
            }, {
              name: "vc_memo",
              label: "3 较急",
              value: "3",
              checked: false,
              type: "radio"
            }, {
              name: "vc_memo",
              label: "4 紧急",
              value: "4",
              checked: false,
              type: "radio"
            }, {
              name: "vc_memo",
              label: "5 特急",
              value: "5",
              checked: false,
              type: "radio"
            }
          ],
          buttons: [
            {
              text: '取消',
              role: 'cancel',
              handler: data => {
                item.checked = false;
              }
            },
            {
              text: '确定',
              handler: data => {
                item.checked = false;
                item["vc_memo"] = data;
                this.bcwRuleService.saveBcwRuleNotify(item, "update").subscribe(saveResult => {
                  console.log("moreOp.saveBcwRuleNotify", saveResult);
                  if (saveResult && saveResult["isSuccess"]) {
                    if (item.vc_memo == '' || item.vc_memo == 1) {

                    }
                    let temp = _.find(this.returnData, {l_ruleid: item["l_ruleid"]});
                    if (temp) {
                      temp["vc_memo"] = data;
                      temp["badge_color"] = this.colorList[parseInt(temp["vc_memo"]) - 1];
                      console.log(this.returnData)
                      this.ruleTree_level1 = [];
                      this.ruleTree_level2 = [];
                      this.ruleTree_level3 = [];
                      this.ruleTree_level4 = [];
                      this.ruleTree_level5 = [];
                      this.ruleTree_level1 = _.filter(this.returnData, d => {
                        if (d["vc_memo"] == "" || d["vc_memo"] == "1") {
                          return true;
                        }
                      });
                      this.ruleTree_level2 = _.filter(this.returnData, {"vc_memo": "2"});
                      this.ruleTree_level3 = _.filter(this.returnData, {"vc_memo": "3"});
                      this.ruleTree_level4 = _.filter(this.returnData, {"vc_memo": "4"});
                      this.ruleTree_level5 = _.filter(this.returnData, {"vc_memo": "5"});
                      console.log(this.ruleTree_level1)
                      console.log(this.ruleTree_level1.length)
                    }
                  }
                  // this.pushDataList = this.returnData.subscribe_list;
                  this.pushDataList = _.sortBy(this.pushDataList, "vc_memo");
                  this.pushDataList = _.reverse(this.pushDataList);
                });
                this.email.login = this.loginid;
                this.email.content = "需要修改等级的规则列表为：" + item.vc_rulename + "；修改的等级为：" + data;
                this.bcwRuleService.editEmail(this.email, 'send').subscribe((data) => {
                  console.log(data);
                })
              }
            }
          ]
        });
        alert.present();
      }
    });
    buttons.push({
      text: "取消",
      role: 'cancel',
      handler: () => {
        item.checked = false;
      }
    });

    let actionSheet = this.actionSheetCtrl.create({
      title: "",
      buttons: buttons
    });

    actionSheet.present();
  }

}


@Directive({
  selector: '[badgeBgColor]'
})
export class BadgeBgColorDirective {

  _el: any;

  data: string;

  constructor(el: ElementRef) {
    // console.log(el);
    this._el = el;
  }

  ngAfterContentInit() {
    // console.log("ngAfterContentInit>>>>>>>>>>>>", this.data);
    if (this.data) {
      this._el.nativeElement.style.backgroundColor = this.data
    }
  }

  ngOnChanges() {
    if (this.data) {
      this._el.nativeElement.style.backgroundColor = this.data
    }
  }

  @Input("badgeBgColor")
  set setData(value) {
    this.data = value;
  }

}
